<template>
  <div class="app-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-container">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.total }}</div>
            <div class="stats-label">总申请数</div>
          </div>
          <div class="stats-icon total">
            <el-icon><User /></el-icon>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number pending">{{ stats.pending }}</div>
            <div class="stats-label">待审核</div>
          </div>
          <div class="stats-icon pending">
            <el-icon><Clock /></el-icon>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number approved">{{ stats.approved }}</div>
            <div class="stats-label">已通过</div>
          </div>
          <div class="stats-icon approved">
            <el-icon><Check /></el-icon>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number rejected">{{ stats.rejected }}</div>
            <div class="stats-label">已拒绝</div>
          </div>
          <div class="stats-icon rejected">
            <el-icon><Close /></el-icon>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快速筛选 -->
    <el-card class="quick-filter-container">
      <div class="quick-filter">
        <span class="filter-label">快速筛选：</span>
        <el-button-group>
          <el-button
            :type="queryParams.status === '' ? 'primary' : ''"
            @click="quickFilter('')"
          >
            全部 ({{ stats.total }})
          </el-button>
          <el-button
            :type="queryParams.status === '1' ? 'primary' : ''"
            @click="quickFilter('1')"
          >
            待认证 ({{ stats.pending }})
          </el-button>
          <el-button
            :type="queryParams.status === '2' ? 'primary' : ''"
            @click="quickFilter('2')"
          >
            已认证 ({{ stats.approved }})
          </el-button>
          <el-button
            :type="queryParams.status === '3' ? 'primary' : ''"
            @click="quickFilter('3')"
          >
            未通过 ({{ stats.rejected }})
          </el-button>
        </el-button-group>
      </div>
    </el-card>

    <!-- 搜索栏 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="queryParams" ref="queryForm">
        <el-form-item label="教师姓名">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入教师姓名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="queryParams.status" placeholder="审核状态" clearable>
            <el-option label="待认证" value="1" />
            <el-option label="已认证" value="2" />
            <el-option label="未通过" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="handleExport">导出数据</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-container">
      <!-- 批量操作栏 -->
      <div class="batch-actions" v-if="selectedRows.length > 0">
        <span class="selected-info">已选择 {{ selectedRows.length }} 项</span>
        <el-button
          type="success"
          size="small"
          @click="handleBatchApprove"
          :disabled="!canBatchApprove"
        >
          批量通过
        </el-button>
        <el-button
          type="danger"
          size="small"
          @click="handleBatchReject"
          :disabled="!canBatchReject"
        >
          批量拒绝
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="reviewList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="教师姓名" prop="name" />
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :src="row.avatar" :size="40"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column label="手机号" prop="phone" width="120" />
        <el-table-column label="邮箱" prop="email" width="180" />
        <el-table-column label="学历" prop="education" width="100" />
        <el-table-column label="专业" prop="major" width="120" />
        <el-table-column label="申请时间" prop="applyTime" width="180" />
        <el-table-column label="审核状态" prop="certificationStatus" width="120">
          <template #default="{ row }">
            <StatusTag :status="row.certificationStatus" type="certification" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">查看</el-button>
            <el-button
              v-if="row.certificationStatus === 1"
              link
              type="success"
              @click="handleApprove(row)"
            >
              通过
            </el-button>
            <el-button
              v-if="row.certificationStatus === 1"
              link
              type="danger"
              @click="handleReject(row)"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog
      title="教师详情"
      v-model="dialog.visible"
      width="700px"
      append-to-body
    >
      <el-descriptions border :column="2">
        <el-descriptions-item label="教师姓名">{{ currentTeacher.name }}</el-descriptions-item>
        <el-descriptions-item label="头像">
          <el-avatar :src="currentTeacher.avatar" :size="60"></el-avatar>
        </el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentTeacher.phone }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ currentTeacher.email }}</el-descriptions-item>
        <el-descriptions-item label="学历">{{ currentTeacher.education }}</el-descriptions-item>
        <el-descriptions-item label="专业">{{ currentTeacher.major }}</el-descriptions-item>
        <el-descriptions-item label="毕业院校">{{ currentTeacher.graduateSchool }}</el-descriptions-item>
        <el-descriptions-item label="教龄">{{ currentTeacher.teachingAge }}年</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ currentTeacher.applyTime }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <StatusTag :status="currentTeacher.certificationStatus" type="certification" />
        </el-descriptions-item>
        <el-descriptions-item label="个人简介" :span="2">
          {{ currentTeacher.introduction }}
        </el-descriptions-item>
        <el-descriptions-item label="资质证书" :span="2">
          <div class="certificate-list">
            <el-image
              v-for="(url, index) in currentTeacher.certificates"
              :key="index"
              :src="url"
              :preview-src-list="currentTeacher.certificates"
              class="certificate-image"
            />
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <div v-if="currentTeacher.rejectReason && currentTeacher.certificationStatus === 3" class="reject-reason">
        <el-alert
          title="拒绝原因"
          type="error"
          :description="currentTeacher.rejectReason"
          show-icon
          :closable="false"
        />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">关闭</el-button>
          <el-button
            v-if="currentTeacher.certificationStatus === 1"
            type="success"
            @click="handleApprove(currentTeacher)"
          >
            通过
          </el-button>
          <el-button
            v-if="currentTeacher.certificationStatus === 1"
            type="danger"
            @click="handleReject(currentTeacher)"
          >
            拒绝
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 拒绝原因对话框 -->
    <el-dialog
      title="拒绝原因"
      v-model="rejectDialog.visible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="rejectFormRefEl"
        :model="rejectForm"
        :rules="rejectRules"
        label-width="80px"
      >
        <el-form-item label="拒绝原因" prop="reason">
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rejectDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitReject">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量拒绝对话框 -->
    <el-dialog
      title="批量拒绝审核"
      v-model="batchRejectDialog.visible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="batchRejectFormRefEl"
        :model="batchRejectForm"
        :rules="rejectRules"
        label-width="80px"
      >
        <el-form-item label="拒绝原因" prop="reason">
          <el-input
            v-model="batchRejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝原因"
          />
        </el-form-item>
        <el-form-item>
          <el-alert
            :title="`将拒绝 ${batchRejectForm.ids.length} 位教师的审核申请`"
            type="warning"
            show-icon
            :closable="false"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="batchRejectDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchReject">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Clock, Check, Close } from '@element-plus/icons-vue'
import { getTeacherReviewList, approveTeacher, rejectTeacher, getTeacherReviewStats, exportTeacherReviewData } from '@/api/teacher'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  status: ''
})

// 数据列表
const reviewList = ref([])
const total = ref(0)
const loading = ref(false)

// 当前教师信息
const currentTeacher = reactive({
  id: undefined,
  name: '',
  avatar: '',
  phone: '',
  email: '',
  title: '',
  subject: '',
  introduction: '',
  certificates: [],
  applyTime: '',
  status: '',
  rejectReason: ''
})

// 对话框控制
const dialog = reactive({
  visible: false
})

// 拒绝对话框
const rejectDialog = reactive({
  visible: false
})

// 拒绝表单
const rejectForm = reactive({
  id: undefined,
  reason: ''
})

// 选中的行
const selectedRows = ref([])

// 表单ref引用
const rejectFormRefEl = ref(null)
const batchRejectFormRefEl = ref(null)

// 批量拒绝表单
const batchRejectForm = reactive({
  ids: [],
  reason: ''
})

// 批量拒绝对话框
const batchRejectDialog = reactive({
  visible: false
})

// 拒绝表单规则
const rejectRules = {
  reason: [
    { required: true, message: '请输入拒绝原因', trigger: 'blur' },
    { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
  ]
}

// 统计数据
const stats = ref({
  total: 0,
  pending: 0,
  approved: 0,
  rejected: 0
})

// 是否可以批量通过
const canBatchApprove = computed(() => {
  return selectedRows.value.every(row => row.certificationStatus === 1)
})

// 是否可以批量拒绝
const canBatchReject = computed(() => {
  return selectedRows.value.every(row => row.certificationStatus === 1)
})

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 2: return 'success'  // 已认证
    case 3: return 'danger'   // 未通过
    case 1:
    default: return 'warning' // 待认证
  }
}

// 状态类型（兼容旧方法）
const statusType = (status) => {
  return getStatusType(status)
}

// 状态文本
const statusText = (status) => {
  switch (status) {
    case 2: return '已认证'
    case 3: return '未通过'
    case 1:
    default: return '待认证'
  }
}

// 获取统计数据
const getStats = async () => {
  try {
    const { data } = await getTeacherReviewStats()
    stats.value = data
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取数据列表
const getList = async () => {
  try {
    loading.value = true
    const { data } = await getTeacherReviewList(queryParams)
    reviewList.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('获取审核列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.name = ''
  queryParams.status = ''
  handleQuery()
}

// 快速筛选
const quickFilter = (status) => {
  queryParams.status = status
  queryParams.pageNum = 1
  getList()
}

// 导出数据
const handleExport = async () => {
  try {
    // 构建导出参数，使用当前的查询条件
    const exportParams = {
      name: queryParams.name,
      status: queryParams.status
    }

    // 调用后端导出API
    const response = await exportTeacherReviewData(exportParams)

    // 创建下载链接
    const blob = new Blob([response], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)

    // 生成文件名
    const now = new Date()
    const dateStr = now.getFullYear() +
      String(now.getMonth() + 1).padStart(2, '0') +
      String(now.getDate()).padStart(2, '0') + '_' +
      String(now.getHours()).padStart(2, '0') +
      String(now.getMinutes()).padStart(2, '0') +
      String(now.getSeconds()).padStart(2, '0')

    link.setAttribute('download', `教师审核数据_${dateStr}.xlsx`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    // 清理URL对象
    URL.revokeObjectURL(url)

    ElMessage.success('数据导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}



// 查看详情
const handleView = (row) => {
  dialog.visible = true
  Object.assign(currentTeacher, row)
}

// 审核通过
const handleApprove = (row) => {
  ElMessageBox.confirm('确认通过该教师的审核吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await approveTeacher(row.id)
      ElMessage.success('审核通过')
      getList()
      getStats() // 更新统计数据
      dialog.visible = false
    } catch (error) {
      console.error('审核操作失败:', error)
    }
  })
}

// 审核拒绝
const handleReject = (row) => {
  rejectDialog.visible = true
  rejectForm.id = row.id
  rejectForm.reason = ''

  // 清除之前的验证状态
  nextTick(() => {
    if (rejectFormRefEl.value) {
      rejectFormRefEl.value.clearValidate()
    }
  })
}

// 提交拒绝
const submitReject = async () => {
  // 表单验证
  const rejectFormRef = rejectFormRefEl.value
  if (!rejectFormRef) {
    ElMessage.error('表单引用错误')
    return
  }

  try {
    // 使用Element Plus的表单验证
    await rejectFormRef.validate()

    // 验证通过，提交数据
    await rejectTeacher({
      id: rejectForm.id,
      reason: rejectForm.reason.trim()
    })

    ElMessage.success('审核已拒绝')
    rejectDialog.visible = false
    dialog.visible = false

    // 重置表单
    rejectFormRef.resetFields()
    rejectForm.reason = ''

    getList()
    getStats() // 更新统计数据
  } catch (error) {
    if (error === false) {
      // 表单验证失败
      ElMessage.error('请检查输入内容')
    } else {
      console.error('审核操作失败:', error)
      ElMessage.error('审核操作失败，请重试')
    }
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 批量审核通过
const handleBatchApprove = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要审核的教师')
    return
  }

  ElMessageBox.confirm(`确认通过选中的 ${selectedRows.value.length} 位教师的审核吗？`, '批量审核', {
    type: 'warning'
  }).then(async () => {
    try {
      const promises = selectedRows.value.map(row => approveTeacher(row.id))
      await Promise.all(promises)
      ElMessage.success('批量审核通过成功')
      selectedRows.value = []
      getList()
      getStats() // 更新统计数据
    } catch (error) {
      console.error('批量审核失败:', error)
      ElMessage.error('批量审核失败，请重试')
    }
  })
}

// 批量审核拒绝
const handleBatchReject = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要拒绝的教师')
    return
  }

  batchRejectDialog.visible = true
  batchRejectForm.ids = selectedRows.value.map(row => row.id)
  batchRejectForm.reason = ''

  // 清除之前的验证状态
  nextTick(() => {
    if (batchRejectFormRefEl.value) {
      batchRejectFormRefEl.value.clearValidate()
    }
  })
}

// 提交批量拒绝
const submitBatchReject = async () => {
  // 表单验证
  const batchRejectFormRef = batchRejectFormRefEl.value
  if (!batchRejectFormRef) {
    ElMessage.error('表单引用错误')
    return
  }

  try {
    // 使用Element Plus的表单验证
    await batchRejectFormRef.validate()

    // 验证通过，提交数据
    const promises = batchRejectForm.ids.map(id =>
      rejectTeacher({
        id: id,
        reason: batchRejectForm.reason.trim()
      })
    )
    await Promise.all(promises)

    ElMessage.success('批量拒绝成功')
    batchRejectDialog.visible = false
    selectedRows.value = []

    // 重置表单
    batchRejectFormRef.resetFields()
    batchRejectForm.reason = ''
    batchRejectForm.ids = []

    getList()
    getStats() // 更新统计数据
  } catch (error) {
    if (error === false) {
      // 表单验证失败
      ElMessage.error('请检查输入内容')
    } else {
      console.error('批量拒绝失败:', error)
      ElMessage.error('批量拒绝失败，请重试')
    }
  }
}

// 初始化
onMounted(() => {
  getList()
  getStats() // 获取统计数据
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .stats-container {
    margin-bottom: 20px;

    .stats-card {
      position: relative;
      overflow: hidden;

      :deep(.el-card__body) {
        padding: 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }

      .stats-content {
        flex: 1;

        .stats-number {
          font-size: 28px;
          font-weight: bold;
          margin-bottom: 5px;
          color: #303133;

          &.pending {
            color: #E6A23C;
          }

          &.approved {
            color: #67C23A;
          }

          &.rejected {
            color: #F56C6C;
          }
        }

        .stats-label {
          font-size: 14px;
          color: #909399;
        }
      }

      .stats-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        color: white;

        &.total {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        &.pending {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }

        &.approved {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }

        &.rejected {
          background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }
      }
    }
  }

  .quick-filter-container {
    margin-bottom: 20px;

    .quick-filter {
      display: flex;
      align-items: center;

      .filter-label {
        margin-right: 15px;
        font-weight: 500;
        color: #303133;
      }
    }
  }

  .filter-container {
    margin-bottom: 20px;
  }

  .table-container {
    .batch-actions {
      padding: 10px 0;
      margin-bottom: 10px;
      border-bottom: 1px solid #ebeef5;
      display: flex;
      align-items: center;
      gap: 10px;

      .selected-info {
        color: #409eff;
        font-size: 14px;
        margin-right: 10px;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .certificate-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

    .certificate-image {
      width: 120px;
      height: 80px;
      border-radius: 4px;
      cursor: pointer;
    }
  }

  .reject-reason {
    margin-top: 20px;
  }
}
</style>
